package com.book.framework.web.service;

import com.book.common.constant.Constants;
import com.book.common.constant.UserConstants;
import com.book.common.core.domain.entity.AppUser;
import com.book.common.core.domain.model.AppLoginUser;
import com.book.common.exception.ServiceException;
import com.book.common.exception.user.UserNotExistsException;
import com.book.common.exception.user.UserPasswordNotMatchException;
import com.book.common.utils.DateUtils;
import com.book.common.utils.MessageUtils;
import com.book.common.utils.StringUtils;
import com.book.common.utils.ip.IpUtils;
import com.book.common.utils.uuid.IdUtils;
import com.book.framework.manager.AsyncManager;
import com.book.framework.manager.factory.AsyncFactory;
import com.book.framework.security.context.AuthenticationContextHolder;
import com.book.system.service.IAppUserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class AppLoginService
{
    private final TokenService tokenService;

    private final AuthenticationManager authenticationManager;

    private final IAppUserService appUserService;;

    public AppLoginService(TokenService tokenService, AuthenticationManager authenticationManager, IAppUserService appUserService) {
        this.tokenService = tokenService;
        this.authenticationManager = authenticationManager;
        this.appUserService = appUserService;
    }

    /**
     * app用户名前缀
     */
    public static final String APP_prefix = "app_";

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password)
    {
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(APP_prefix + username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordAppLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordAppLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordAppLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        AppLoginUser loginUser = (AppLoginUser) authentication.getPrincipal();
        // 生成token
        String token = IdUtils.fastUUID();
        //记录登录信息
        recordLoginInfo(loginUser.getUserId(),token);
        return tokenService.createToken(loginUser,token);
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     * @param token token
     */
    public void recordLoginInfo(String userId,String token)
    {
        AppUser appUser = new AppUser();
        appUser.setId(userId);
        appUser.setLoginIp(IpUtils.getIpAddr());
        appUser.setLoginDate(DateUtils.getNowDate());
        appUser.setLastToken(token);
        appUserService.updateById(appUser);
    }
}
